package com.example.bzh.gamecat.ui.cattery.personal;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bzh.gamecat.R;
import com.example.bzh.gamecat.bean.HotTag;
import com.example.bzh.gamecat.bean.UserBean;
import com.example.bzh.gamecat.dao.HotTagBeanDao;
import com.example.bzh.gamecat.dao.UserBeanDao;
import com.fyales.tagcloud.library.TagBaseAdapter;
import com.fyales.tagcloud.library.TagCloudLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class PersonalCenterActivity extends AppCompatActivity {

    @BindView(R.id.iv_personal_back)
    ImageView ivPersonalBack;
    @BindView(R.id.level_has)
    TextView levelHas;
    @BindView(R.id.experience_has)
    TextView experienceHas;
    @BindView(R.id.experience_all)
    TextView experienceAll;
    @BindView(R.id.level_next)
    TextView levelNext;
    @BindView(R.id.experience_bar)
    ImageView experienceBar;
    @BindView(R.id.personal_miao_num)
    TextView personalMiaoNum;
    @BindView(R.id.personal_copy_num)
    TextView personalCopyNum;
    @BindView(R.id.personal_head_image)
    ImageView personalHeadImage;
    @BindView(R.id.head_back)
    ImageView headBack;
    @BindView(R.id.personal_setHeadImage)
    RelativeLayout personalSetHeadImage;
    @BindView(R.id.personal_name)
    TextView personalName;
    @BindView(R.id.name_back)
    ImageView nameBack;
    @BindView(R.id.personal_setName)
    RelativeLayout personalSetName;
    @BindView(R.id.personal_sex)
    TextView personalSex;
    @BindView(R.id.sex_back)
    ImageView sexBack;
    @BindView(R.id.personal_setSex)
    RelativeLayout personalSetSex;
    @BindView(R.id.personal_birth)
    TextView personalBirth;
    @BindView(R.id.birth_back)
    ImageView birthBack;
    @BindView(R.id.personal_setBirth)
    RelativeLayout personalSetBirth;
    @BindView(R.id.personal_society)
    TextView personalSociety;
    @BindView(R.id.personal_setSociety)
    RelativeLayout personalSetSociety;

    TextView hot8;
    @BindView(R.id.btn_hot1)
    Button btnHot1;
    @BindView(R.id.btn_hot2)
    Button btnHot2;
    @BindView(R.id.btn_hot3)
    Button btnHot3;
    @BindView(R.id.btn_hot4)
    Button btnHot4;
    @BindView(R.id.btn_hot5)
    Button btnHot5;
    @BindView(R.id.btn_hot6)
    Button btnHot6;
    @BindView(R.id.btn_hot7)
    Button btnHot7;
    @BindView(R.id.btn_hot8)
    Button btnHot8;
    @BindView(R.id.hot_tag)
    TagCloudLayout hotTag;
    private Unbinder unbinder;
    private String catNum;
    private PopupWindow popupWindow;

    private ImageView ivHead;//头像显示
    private Bitmap head;//头像Bitmap
    private static String path = "/sdcard/myHead/";//sd路径

    private TextView popCarema;//拍照
    private TextView popChoPhoto;//相册
    private TextView popCancel;
    private PopupWindow popSex;
    private View mainView;
    private TextView chooseMan;
    private TextView chooseWomen;
    private TextView sexCancel;
    private List<String> hotList;
    private TagBaseAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_personal_center);
        unbinder = ButterKnife.bind(this);
        mainView = LayoutInflater.from(this).inflate(R.layout.activity_personal_center, null);
        Bitmap bt = BitmapFactory.decodeFile(path + "head.jpg");//从Sd中找头像，转换成Bitmap
        if (bt != null) {
            @SuppressWarnings("deprecation")
            Drawable drawable = new BitmapDrawable(bt);//转换成drawable
            personalHeadImage.setImageDrawable(drawable);
        } else {
            /**
             *	如果SD里面没有则需要从服务器取头像，取回来的头像再保存在SD中
             *
             */
        }

        hotList = new ArrayList<>();
        final HotTag hot = new HotTag();
        final List<HotTag> hotTags = HotTagBeanDao.queryAll(this, hot);

        for (int i=0;i<hotTags.size();i++){
            hotList.add(hotTags.get(i).getTag());
        }

        adapter = new HotTagAdapter(this,hotList);
        hotTag.setAdapter(adapter);

        hotTag.setItemClickListener(new TagCloudLayout.TagItemClickListener() {
            @Override
            public void itemClick(int position) {

                HotTag hotBean = new HotTag();

                hotBean.setTag(hotList.get(position));
                HotTagBeanDao.del(PersonalCenterActivity.this,hotBean);
                hotList.remove(position);

                adapter.notifyDataSetChanged();
            }
        });


    }

    @OnClick({R.id.iv_personal_back, R.id.personal_copy_num, R.id.personal_setHeadImage,
            R.id.personal_setName, R.id.personal_setSex, R.id.personal_setBirth})
    public void onItemClick(View view) {

        switch (view.getId()) {
            case R.id.iv_personal_back: //关闭
                finish();
                break;
            case R.id.personal_copy_num: //复制喵号
                catNum = personalMiaoNum.getText().toString().trim();
                Toast.makeText(this, "复制瞄号成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.personal_setHeadImage: //修改头像

                getUpdateHeadImage(mainView);
                break;
            case R.id.personal_setName: //修改昵称
                updateName();
                break;
            case R.id.personal_setSex: //设置性别
                getUpdateSex(mainView);
                break;
            case R.id.personal_setBirth:
                birthdayDialog();
                break;
        }

    }

    /**
     * 热门标签
     *
     * @param view
     */
    @OnClick({R.id.btn_hot1, R.id.btn_hot2, R.id.btn_hot3, R.id.btn_hot4, R.id.btn_hot5, R.id.btn_hot6, R.id.btn_hot7, R.id.btn_hot8})
    public void onHotClick(View view) {
        Log.i("size","Size="+hotList.size());
        if (hotList.size()>8-1){
            Toast.makeText(PersonalCenterActivity.this,"标签不能超过八个",Toast.LENGTH_SHORT).show();
            return;
        }
        HotTag hotTag = new HotTag();
        switch (view.getId()) {

            case R.id.btn_hot1:
                String s1 = btnHot1.getText().toString();
                hotList.add(s1);
                hotTag.setTag(s1);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot2:
                String s2 = btnHot2.getText().toString();
                hotList.add(s2);
                hotTag.setTag(s2);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot3:
                String s3 = btnHot3.getText().toString();
                hotList.add(s3);
                hotTag.setTag(s3);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot4:
                String s4 = btnHot4.getText().toString();
                hotList.add(s4);
                hotTag.setTag(s4);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot5:
                String s5 = btnHot5.getText().toString();
                hotList.add(s5);
                hotTag.setTag(s5);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot6:
                String s6 = btnHot6.getText().toString();
                hotList.add(s6);
                hotTag.setTag(s6);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot7:
                String s7 = btnHot7.getText().toString();
                hotList.add(s7);
                hotTag.setTag(s7);
                HotTagBeanDao.add(this,hotTag);
                break;
            case R.id.btn_hot8:
                break;

        }

        adapter.notifyDataSetChanged();

    }


    //修改昵称
    private void updateName() {
        Intent intent = new Intent(this, UpdatePersonalNameActivity.class);
        intent.putExtra("name", personalName.getText().toString().trim());
        startActivityForResult(intent, 4);
        overridePendingTransition(R.anim.in_from_right, R.anim.keep);
    }

    //修改性别
    public void getUpdateSex(View view) {
        View sexView = LayoutInflater.from(this).inflate(R.layout.pop_update_sex, null);
        popSex = new PopupWindow(sexView, 600, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popSex.showAtLocation(view, Gravity.CENTER, 0, 0);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.7f;
        getWindow().setAttributes(params);

        sexView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (popSex != null && popSex.isShowing()) {
                    closePopupWindow(popSex);
                }
                return false;
            }
        });
        chooseMan = (TextView) sexView.findViewById(R.id.pop_choose_man);
        chooseWomen = (TextView) sexView.findViewById(R.id.pop_choose_women);
        sexCancel = (TextView) sexView.findViewById(R.id.pop_sex_cancel);

        chooseMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                personalSex.setText(chooseMan.getText().toString().trim());
                closePopupWindow(popSex);
            }
        });
        chooseWomen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                personalSex.setText(chooseWomen.getText().toString().trim());
                closePopupWindow(popSex);
            }
        });
        sexCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closePopupWindow(popSex);
                // popSex.dismiss();
            }
        });
    }

    //显示选择日期的dialog
    private void birthdayDialog() {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                personalBirth.setText(year + "-" + monthOfYear + "-" + dayOfMonth);

                Toast.makeText(PersonalCenterActivity.this, year + "." + monthOfYear + "." + dayOfMonth, Toast.LENGTH_SHORT).show();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.setCancelable(true);
        datePickerDialog.show();
    }


    /**
     * 关闭窗口
     */
    private void closePopupWindow(PopupWindow popupWindow) {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
            WindowManager.LayoutParams params = getWindow().getAttributes();
            params.alpha = 1f;
            getWindow().setAttributes(params);
        }
    }

    //    修改头像
    public void getUpdateHeadImage(View view) {
        View popView = LayoutInflater.from(this).inflate(R.layout.pop_update_headimage, null);
        popupWindow = new PopupWindow(popView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.7f;
        getWindow().setAttributes(params);
        // 点击其他地方消失
        popView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (popupWindow != null && popupWindow.isShowing()) {
                    closePopupWindow(popupWindow);
                }
                return false;
            }
        });
        popCarema = (TextView) popView.findViewById(R.id.pop_carema);
        popChoPhoto = (TextView) popView.findViewById(R.id.pop_choose_photo);
        popCancel = (TextView) popView.findViewById(R.id.pop_cancel);

        //从相册里面取照片
        popChoPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
            }
        });
        //调用相机拍照
        popCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                        "head.jpg")));
                startActivityForResult(intent2, 1);//采用ForResult打开
            }
        });


        popCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());//裁剪图片
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    File temp = new File(Environment.getExternalStorageDirectory()
                            + "/head.jpg");
                    cropPhoto(Uri.fromFile(temp));//裁剪图片
                }
                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);//保存在SD卡中
                        personalHeadImage.setImageBitmap(head);//用ImageView显示出来
                    }
                }
                break;
            case 4:
                String updateName = data.getStringExtra("updateName");
                personalName.setText(updateName);
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    /**
     * 调用系统的裁剪
     *
     * @param uri
     */
    public void cropPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        File file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";//图片名字
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }


}
